package com.gzz.orchid.common.core.validation.validator;

import jakarta.validation.Constraint;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;

import java.lang.annotation.*;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 定义了注解 AnnoValidator 用来校验 anno 字段，只能存放1，2，3之中的一个字符串数字
 *
 * @AnnoValidator(value = "1,2,3")
 * private String anno;
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.ANNOTATION_TYPE})
//指定注解的处理类
@Constraint(validatedBy = AnnoValidator.Validator.class)
public @interface AnnoValidator {

    String value();

    String message() default "AnnoValidator 不存在";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class Validator implements ConstraintValidator<AnnoValidator, Object> {

        private String value;

        @Override
        public void initialize(AnnoValidator constraintAnnotation) {
            this.value = constraintAnnotation.value();
        }

        @Override
        public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
            List<String> list = Arrays.asList(value.split(","));
            final AtomicBoolean flag = new AtomicBoolean(false);
            list.forEach(one -> {
                if (one.equals(o)) {
                    flag.set(true);
                }
            });
            return flag.get();
        }

    }
}
